/**
 * Project Name:PlaceOrderService.java
 * File Name:PlaceOrderService.java
 * Date:2018/7/28 上午9:57
 * Copyright (c) 2018, zhang.xiangyu@foxmail.com All Rights Reserved.
*/
package com.meatball.api.pay.service;

import com.meatball.api.pay.params.PlaceOrderParams;
import com.meatball.base.pay.order.service.UnifiedPayService;
import com.meatball.base.pay.order.vo.PayOrderParams;
import com.meatball.base.pay.utils.AlipayTradePrecreate;
import com.meatball.utils.AlipayResRedder;
import com.meatball.vo.ResultMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Title: PlaceOrderService.java
 * @Description: todo(统一支付接口服务)
 * @Author 張翔宇
 * @Date 2018/7/28 上午9:57
 * @Version V1.0
 */
@Slf4j
@Service
public class PayApiService {
    @Resource
    private AlipayTradePrecreate alipayTradePrecreate;
    @Resource
    private UnifiedPayService unifiedPayService;

    /**
     * @Title: placeOrder
     * @Description: todo(统一下单接口)
     * @Params:
     * @Return     返回类型
     * @Author 張翔宇
     * @Date 2018/7/28 下午9:50
     */
    public ResultMsg placeOrder (PlaceOrderParams record) {
        PayOrderParams params = new PayOrderParams();
        BeanUtils.copyProperties(record, params);
        params.setOutTradeNo("WPH" + System.currentTimeMillis());
        return unifiedPayService.unifiedPay(params);
    }

    /**
     * @Title: payment
     * @Description: todo(统一扫码解析)
     * @Params: id: 订单ID，ua：User-Agent
     * @Return     返回类型
     * @Author 張翔宇
     * @Date 2018/7/30 上午8:28
     */
    public ResultMsg payment(Long id, String ua) throws Exception {
        return unifiedPayService.payment(id, ua);
    }

    /**
     * @Title: alipayCallback
     * @Description: todo(支付宝回调)
     * @Params:
     * @Return     返回类型
     * @Author 張翔宇
     * @Date 2018/7/31 上午9:41
     */
    public ResultMsg alipayCallback(HttpServletRequest request) throws Exception {
        return unifiedPayService.alipayCallback(request);
    }

    /**
     * @Title: paySyncSuccess
     * @Description: todo(通知)
     * @Params:
     * @Return     返回类型
     * @Author 張翔宇
     * @Date 2018/7/31 下午10:03
     */
    public ResultMsg paySyncSuccess(HttpServletRequest request) {
        Map<String, String> maps = AlipayResRedder.read(request);
        // 验签结果
        boolean verify  = alipayTradePrecreate.verifySignature(maps);
        if (verify) {
            Map<String, String> map = new HashMap<>();
            map.put("outTradeNo", maps.get("out_trade_no"));
            map.put("totalAmount", maps.get("total_amount"));
            return new ResultMsg(200, "支付成功。", map);
        }
        return null;
    }
}
